package com.cysd.ewmksbs.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.cszy.ewmxns.base.BaseVMActivity
import com.cszy.ewmxns.ext.launch
import com.cszy.ewmxns.ext.toast

import com.cysd.ewmksbs.ksb_ui.dialog.PermissoTipDialog
import com.cysd.ewmksbs.ksb_ui.dialog.UserRefusedPermissonDialog

import com.cysd.ewmksbs.ui.fragment.Ksb_ScanErrorDialog
import com.cysd.ewmksbs.ksb_utils.FlashlightController
import com.cysd.ewmksbs.ksb_utils.SpUtils
import com.cysd.ewmksbs.viewmodel.MainViewModel
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions
import com.csylhl.ewmksb.R
import com.csylhl.ewmksb.databinding.ActivityQrcodeBinding
import com.cszy.ewmxns.ext.isFinish
import com.hnyyac.ad.mds.IAdToActivityListener
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener


class Ksb_QrcodeActivity : BaseVMActivity<MainViewModel, ActivityQrcodeBinding>(), IAdViewListener {
    private var pernissonTopdialog: PermissoTipDialog? = null
    private var qrType = 0    //0 二维码  1 条形码
    private lateinit var flashlightController: FlashlightController
    private var type: String? = null
    var app_progress: String? = null


    /**
     * 写一个启动自己的方法 而且带参数type 每次启动进来会谈激励广告
     */
    companion object {
        fun launch(context: Context, type: String) {
            var hasStarted = false
            fun startAc() {
                if (hasStarted) return
                hasStarted = true
                val bundle = Bundle()
                bundle.putString("type", type)
                context.launch(bundle, Ksb_QrcodeActivity::class.java)
            }

            var app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
            if (app_process == "0") {
                startAc()
                return
            }

            AdManager.loadVideoAndJumpAc(context as Activity, 5, object : IAdToActivityListener {
                override fun onAdToActivity() {
                    startAc()
                }
            })
        }
    }

    // 注册启动器和结果处理器
    private val barcodeLauncher = registerForActivityResult<ScanOptions, ScanIntentResult>(
        ScanContract()

    ) { result: ScanIntentResult ->
        showLoading("正在识别中，请稍后")
        if (result.contents == null) {
            Toast.makeText(this, "已取消", Toast.LENGTH_LONG).show()
            dismissLoading()
            // 返回后恢复二维码扫描
            startScanner()

        } else {
            var str = result.contents
            var bundle = Bundle()
            bundle.putString("scanResult", str)
            launch(bundle, Ksb_ScanResultActivity::class.java)
            finish()

        }
    }

    //本地图片获取
    @SuppressLint("SuspiciousIndentation")
    private val legacyPickLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            val uri = result.data?.data // 获取单选图片 Uri
            showLoading("正在识别中，请稍后")
            if (uri != null) {
                dismissLoading()
                try {
                    // 将 URI 转换为 Bitmap
                    val bitmap = getBitmapFromUri(uri)
                    if (bitmap != null) {
                        // 使用 ZXing 解析二维码/条形码
                        val result = decodeQRCode(bitmap)

                        if (result != null) {
                            // 识别成功，处理结果
                            handleScanResult(result)
                        } else {
                            // 识别失败
                            showDialog_scan()
                        }
                    } else {
                        showDialog_scan()
                    }
                } catch (e: Exception) {
                    showDialog_scan()
                } finally {
                    dismissLoading()
                }

            } else {
                dismissLoading()
                showDialog_scan()
            }

        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.headTitle.headBack.setImageResource(R.mipmap.ic_back)
        //mBinding.headTitle.headRelative.setBackgroundColor(resources.getColor(R.color.black))
        mBinding.headTitle.headCenterTitle.text = "扫一扫"
        flashlightController = FlashlightController(this)
        app_progress = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        if (app_progress == "0") {
            mBinding.rvTxm.visibility = View.VISIBLE
            mBinding.rvEwm.visibility = View.VISIBLE
        } else {
            mBinding.rvTxm.visibility = View.INVISIBLE
            mBinding.rvEwm.visibility = View.INVISIBLE
        }

    }

    @SuppressLint("SuspiciousIndentation")
    override fun initData() {
        type = intent.getStringExtra("type")
        if (app_progress == "0") {
            if (XXPermissions.isGranted(this@Ksb_QrcodeActivity, Manifest.permission.CAMERA)) {
                // 监听扫描结果
                if (qrType == 0) {
                    startScanner()
                } else {
                    startScannerForTxm()
                }

            } else {
                request_Permission(
                    this@Ksb_QrcodeActivity,
                    Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }
        } else {
            loadInsertAd()
        }
    }

    private fun loadInsertAd() {
        AdManager.loadChapin_nocache(
            this@Ksb_QrcodeActivity,
            19,
            this@Ksb_QrcodeActivity,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    if (isFinish())return
                    if (XXPermissions.isGranted(
                            this@Ksb_QrcodeActivity,
                            Manifest.permission.CAMERA
                        )
                    ) {
                        // 监听扫描结果
                        startScanner()
                    } else {
                        request_Permission(
                            this@Ksb_QrcodeActivity,
                            Manifest.permission.CAMERA,
                            "相机",
                            "需要获取您的相机权限用来扫描二维码"
                        )
                    }
                }
            })
    }

    override fun initListener() {
        mBinding.headTitle.headBack.setOnClickListener {
            finish()
        }
        //条形码识别
        mBinding.rvTxm.setOnClickListener {
            qrType = 1;
            startScannerForTxm()
            toast("已切换条形码识别")
        }
        //二维码识别
        mBinding.rvEwm.setOnClickListener {
            qrType = 0;
            startScanner()
            toast("已切换二维码识别")
        }

        //本地图片识别
        mBinding.ivLocal.setOnClickListener {
            if (XXPermissions.isGranted(this, Manifest.permission.READ_MEDIA_IMAGES)) {
                // 获取相册
                openLegacyGallery()
            } else {
                request_Permission(
                    this,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    "相册",
                    "需要获取您的相册权限来选择图片"
                )
            }
        }

    }

    /**
     * 二维码识别启动
     */
    private fun startScanner() {
        mBinding.barcodeScanner.apply {
            // 确保先暂停再重新开始
            pause()
            resume()
            // 设置扫描回调
            decodeSingle(object : BarcodeCallback {
                override fun barcodeResult(result: BarcodeResult) {
                    if (result.text?.isNotEmpty() == true) {
                        pause() // 扫描成功后暂停
                        handleScanResult(result.text)
                    }
                }
            })
        }
    }

    /**
     * 条形码识别启动
     */
    private fun startScannerForTxm() {
        val options = ScanOptions()
        options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES)
        options.setPrompt("扫描条形码")
        options.setCameraId(0) // 使用设备的特定摄像头
        options.setBeepEnabled(true)
        options.setBarcodeImageEnabled(true)
        options.setOrientationLocked(false)
        barcodeLauncher.launch(options)
    }

    fun handleScanResult(result: String) {
        var bundle = Bundle()
        bundle.putString("scanResult", result)

        when (type) {
            "general" -> {
                if (app_progress == "0") {
                    launch(bundle, Ksb_ScanResultActivity::class.java)
                } else {
                    launch(bundle, LoadingQrcodeProGressActivity::class.java)
                }

            }

            "wifi" -> {
                if (app_progress == "0") {
                    launch(bundle, Ksb_WifiResultActivity::class.java)
                } else {
                    launch(bundle, LoadingQrcodeProGressActivity::class.java)
                }

            }

            else -> launch(bundle, Ksb_ScanResultActivity::class.java)
        }
        finish()

    }

    fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        // 检查是否已标记为"不再询问"
        if (!SpUtils.getInstance().getBoolean(permisson_name)) { // 没有获取该权限或者没有永久拒绝
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            // 申请单个权限
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (pernissonTopdialog != null) {
                        pernissonTopdialog!!.dismiss()
                    }
                    if (!allGranted) {

                        toast("获取 $permisson_name 权限成功")
                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    toast("获取 $permisson_name 权限成功")
                    // 改为调用startScanner()方法
                    when (permisson_name) {
                        "相机" -> {
                            if (qrType == 0) {
                                startScanner()
                            } else {
                                startScannerForTxm()
                            }
                        }

                        "相册" -> {
                            openLegacyGallery()
                        }
                    }
                    if (qrType == 0) {
                        startScanner()
                    } else {
                        startScannerForTxm()
                    }

                }

                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        showDoNotAskAgainDialog(
                            this@Ksb_QrcodeActivity,
                            req_permisson,
                            permisson_name
                        )
                    } else {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        finish()
                    }
                }
            })
    }

    /**
     * 用户单次拒绝
     */
    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }

    /**
     * 用户多次拒绝
     */
    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = UserRefusedPermissonDialog(context, permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }

    fun openLegacyGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        legacyPickLauncher.launch(intent)
    }

    /**
     * 扫描错误弹窗
     */
    fun showDialog_scan() {
        var dialog = Ksb_ScanErrorDialog(this)
        dialog.show()
    }

    // 从 URI 获取 Bitmap
    private fun getBitmapFromUri(uri: Uri): Bitmap? {
        return try {
            val inputStream = contentResolver.openInputStream(uri)
            BitmapFactory.decodeStream(inputStream)
        } catch (e: Exception) {
            null
        }
    }

    private fun decodeQRCode(bitmap: Bitmap): String? {
        try {
            val intArray = IntArray(bitmap.width * bitmap.height)
            bitmap.getPixels(intArray, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

            val source = RGBLuminanceSource(bitmap.width, bitmap.height, intArray)
            val binaryBitmap = BinaryBitmap(HybridBinarizer(source))

            // 可以尝试多种格式
            val formats = listOf(
                BarcodeFormat.QR_CODE,
                BarcodeFormat.EAN_13,
                BarcodeFormat.EAN_8,
                BarcodeFormat.UPC_A,
                BarcodeFormat.UPC_E,
                BarcodeFormat.CODE_128,
                BarcodeFormat.CODE_39,
                BarcodeFormat.ITF
            )

            val hints = mapOf(
                DecodeHintType.POSSIBLE_FORMATS to formats,
                DecodeHintType.TRY_HARDER to true
            )

            val reader = MultiFormatReader()
            val result = reader.decode(binaryBitmap, hints)
            return result.text
        } catch (e: NotFoundException) {
            // 未找到二维码/条形码
            return null
        } catch (e: Exception) {
            // 其他错误
            return null
        }

    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        // 检查 Fragment 是否仍然有效
        // 检查 Activity 是否有效
        if (isFinish())return
        if (XXPermissions.isGranted(this@Ksb_QrcodeActivity, Manifest.permission.CAMERA)) {
            // 监听扫描结果
            startScanner()
        } else {
            request_Permission(
                this@Ksb_QrcodeActivity,
                Manifest.permission.CAMERA,
                "相机",
                "需要获取您的相机权限用来扫描二维码"
            )
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

}